import uuid
# from flaskapp.model.db import db, User
from flaskapp.model.mongo import db
from bson import ObjectId
# from sqlalchemy.exc import SQLAlchemyError
from datetime import datetime
import logging

# Setup logging
logger = logging.getLogger(__name__)

def insert(username: str, password: str,telephone:str =None,email:str =None) -> bool:
    try:
        current_datetime = datetime.now()
        #info = User(id=str(uuid.uuid4()), username=username,password=password,telephone=telephone,email=email, timestamp=current_datetime)
        # db.session.add(info)
        # db.session.commit()
        info ={ "username":username,"password":password,"telephone":telephone,"email":email, "timestamp":current_datetime}
        db.users.insert_one(info)
        logger.info(f"Inserted user with id: {info.id}")
        return True
    except BaseException as e:
        #db.session.rollback()
        logger.error(f"Error inserting user: {e}")
        return False

def delete(id: str) -> bool:
    try:
        info = db.users.find_one({"_id":ObjectId(id)})
        if info:
            # db.session.delete(info)
            # db.session.commit()
            db.users.delete_one({"_id":ObjectId(id)})
            logger.info(f"Deleted alarm with id: {info._id}")
            return True
        logger.warning(f"User with id: {id} not found")
        return False
    except BaseException as e:
        #db.session.rollback()
        logger.error(f"Error deleting user: {e}")
        return False
def exist(name: str) -> bool:
    try:
        condition = {'username': name}
        count = db.users.count_documents(condition)
        # count = User.query.filter(User.username==name).count()
        return count
    except BaseException as e:
        logger.error(f"Error deleting user: {e}")
        return 0        

def findOne(name: str) -> bool:
    try:
        # row = User.query.filter(User.username==name).first()
        row=db.users.find_one({"username":name})
        return row
    except BaseException as e:
        logger.error(f"Error deleting user: {e}")
        return 0   

def get(page: int = 1, per_page: int = 10, username: str = None) -> dict:
    try:
        logger.info(f"Fetching users for page: {page}, per_page: {per_page}, username: {username}")
        # query = User.query.order_by(User.timestamp.desc())
        
        total = db.users.count_documents({})
        users_page=db.users.find({}).sort("timestamp").limit(per_page).skip(per_page*(page-1))
        users=[]
        for r in users_page:
            users.append(r)
        # pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        # users = [user.to_dict() for user in pagination.items]
        # logger.info(f"Retrieved {len(users)} users from page {page}, total items: {pagination.total}, total pages: {pagination.pages}")
        return {
            "items": users,
            "total": total
        }
    except BaseException as e:
        logger.error(f"Error retrieving users: {e}")
        return {"users": [], "total_pages": 0, "current_page": 0, "total_items": 0}


def update(id: str, username: str, password: str,telephone:str =None,email:str =None) -> bool:
    try:
        #info = User.query.get(id)
        info = db.users.find_one({"_id":ObjectId(id)})
        if info:
            info.username = username
            info.password = password
            info.telephone = telephone
            info.email = email
            info.timestamp = datetime.now()  # 更新修改时间
            db.users.update_one(info)
            logger.info(f"Updated user with id: {info._id}")
            return True
        logger.warning(f"User with id: {id} not found")
        return False
    except BaseException as e:
        # db.session.rollback()
        logger.error(f"Error updating task: {e}")
        return False
